#!/usr/bin/env node

const http=require('http'),
      log=console.log,
      qs=require('querystring'),
      fs=require('fs');

let items=[],
    result={
      status:200,
      reason:'ok',
      data:[],
      count:0
    };
http.createServer((req,res)=>{
  logRequest(req);
  //接口服务
  if(req.url.slice(0,5)!=='/todo'){
    let html=fs.readFileSync('./index.html').toString('utf8');
    if(req.url==='/'){
      res.end(html);
    }else if(req.url=='/12-todo.js'){
      fs.createReadStream('./12-todo.js').pipe(res);

    }else{
      res.end('not api request and not page request')
    }
    return;
  }
  switch (req.method){
    case 'GET':
      //查询操作
      select(req,res);
      break;
    case 'POST':
      insert(req,res);
           break;
    case 'PUT':
      //修改操作
      update(req,res);
          break;
    case 'DELETE':
      //删除操作
      remove(req,res);
         break;
    default:
      //返回给客户端的
      res.end(`${req.method} method not suppose`);
      break;
  }


}).listen(8080);



function logRequest(req){
  let str=`${req.method} ${req.url}  HTTP/${req.httpVersion}`;
  log(str);
  log(req.headers);
  log();
}

function select(req,res){
  //查询操作
  result.data=items;
  res.end(JSON.stringify(result));
}

function insert(req,res){
  let data='';
  req.on('data',chunk=>data+=chunk);
  req.on('end',()=>{
    let item= qs.parse(data).item;
    if(item!==''&&typeof item!==undefined){
      items.push(item);
      res.end(JSON.stringify(result));
    }else{
      result.status=401;
      result.reason='item is empty';
      res.end(result);
    }

  });
}

function update(req,res){
  //get id get item 然后就修改对应的值
  let id=req.url.split(':')[1];
  //id校验
  let data='';
  req.on('data',(chunk)=>data+=chunk);
  res.on('end',()=>{
    console.log('put end');
    let item = qs.parse(data).item;
    if(item!==''&& typeof item!=='undefinde'){
      items[id]=item;
      res.end(result);
    }else{
      result.status=402;
      result.reason='itme is empty';
      res.end(result);
    }
  });
}

function remove(req,res){
  //get id 
  //id not exit del all
  //id exit del id item
  
  let id=req.url.split(':')[1];
  if(typeof id ==='undefined'){
    items=[];
    result.status=200;
    result.reason='delete all sucess';
    res.end(JSON.stringify(result));
    return;
  }
  items= items.splice(id,1);
  result.status=200;
  result.reason='delete success';
  res.end(JSON.stringify(result));
}
